﻿#include "stu_infor_manage.h"
#include "ui_stu_infor_manage.h"
#include"maininterface.h"
#include<QDir>
#include<QDebug>
#include<QLineEdit>
#include<QLabel>
#include<QMessageBox>
#include<vector>
#include<QProcess>
#include<QFileDialog>
#include<string>
#include<QSqlQuery>
#include<QSqlDatabase>
#include<QDesktopServices>
#include <QUrl>
stu_infor_Manage::stu_infor_Manage(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::stu_infor_Manage)
{
    ui->setupUi(this);

    //bool stop = false;
    //训练好的文件名称，放置在可执行文件同目录下
    cascade_1.load("G:\\haarcascade_frontalface_alt2.xml");
    train= new TrainThread(this);//执行父对象，方便内存回收

    connect(&timer_2,&QTimer::timeout,this,&stu_infor_Manage::readframe);
    connect(train,&TrainThread::finished,this,&stu_infor_Manage::train_over);
    QSqlDatabase db=QSqlDatabase::addDatabase("QSQLITE");//设置数据库驱动
    db.setDatabaseName("G:\\Admin.db");//创建数据
    if(!db.open())
    {
        qDebug()<<"open error";
    }




}

stu_infor_Manage::~stu_infor_Manage()
{
    delete ui;
    qDebug()<<"ccccccc";
}

//打开摄像头响应函数响应
void stu_infor_Manage::on_OpenCam_pressed()
{

capture.open(0,cv::CAP_DSHOW);
timer_2.start(20);
}


void stu_infor_Manage::readframe()
{
    capture>>frame;

    cvtColor(frame,gray,COLOR_BGR2GRAY);
     equalizeHist(gray, gray); //变换后的图像进行直方图均值化处理
    cascade_1 .detectMultiScale(gray,faces,1.1,3,CASCADE_DO_ROUGH_SEARCH,Size(70,70),Size(500,500));
    for(int i=0;i<faces.size();i++)
    {
        //qDebug()<<faces.size()+3;
        rectangle(frame,faces[i],Scalar(255,0,0),2,8,0 );
    }

    cvtColor(frame,frameRGB,COLOR_BGR2RGB );
    QImage image(frameRGB.data,frameRGB.cols,frameRGB.rows,frameRGB.step1(),QImage::Format_RGB888);
   // QImage image(frame.data,frame.cols,frame.rows,frame.step1(),QImage::Format_RGB888);
    QPixmap pixmap=QPixmap::fromImage(image);
    ui->label_show->setScaledContents(true);
    ui->label_show->setPixmap(pixmap);
    ui->label_show->show();

}
//采集人脸图片
void stu_infor_Manage::on_pBcollect_clicked()
{
    //创建保存目录
    QDir dir;
    dir_str="F:\\Image\\Imagedata\\";
if (!ui->numberEdit->text().isEmpty()&&!ui->nameEdit->text().isEmpty())
{
    if(!dir.exists(dir_str+ui->numberEdit->text()+"_"+ui->nameEdit->text()))
    {
        bool save_dir=dir.mkdir(dir_str+ui->numberEdit->text()+"_"+ui->nameEdit->text());
        qDebug()<<save_dir;
    }
 }
else
{
    QMessageBox::about(this,QString::fromLocal8Bit("提示"),QString::fromLocal8Bit("请输入学生信息"));
    return;
}

    ui->label_numshow->setText(QString::number(pic_num)+QString::fromLocal8Bit("张"));

    if(faces.size()==1  )
    {
        Mat ROIface=gray(faces[0]);

        cv::resize(ROIface,myface,Size(92,112));

        cvtColor(frame,frame,COLOR_BGR2RGB  );
        QImage image(frame.data,frame.cols,frame.rows,frame.step1(),QImage::Format_RGB888);
        QPixmap pixmap=QPixmap::fromImage(image);
        ui->label_collect->setScaledContents(true);
        ui->label_collect->setPixmap(pixmap);

        //保存人脸

        cvtColor(myface,myface,COLOR_GRAY2RGB);
        QString Facefile=dir_str+ui->numberEdit->text()+"_"+ui->nameEdit->text()+"\\"+QString::number(pic_num)+".jpg";
        //QString::number把pic_num转成QString
        Face_save=Facefile.toLocal8Bit().toStdString();//QString先转为本地编码，再转为string
        cv::imwrite(Face_save,myface);
        pic_num++;
    }
}
//关闭摄像头
void stu_infor_Manage::on_CloseCam_clicked()
{
    timer_2.stop();
    capture.release();
    pic_num =0;
    ui->label_numshow->setText(QString::number(pic_num)+QString::fromLocal8Bit("张"));
}
//生成训练文件
void stu_infor_Manage::on_pBtrain_clicked()
{
    QProcess mprocess ;
    try {
        QStringList params;
        QString str = "E:\\run.bat";
        params << "/c" << str;
        mprocess.start("cmd.exe");
        qDebug()<<"nnnnnnnn";

    }
       catch (cv::Exception& e) {
            QMessageBox::about(this,"提示","文件生成失败");
            return ;
        }
       QMessageBox::about(this,QString::fromLocal8Bit("提示"),QString::fromLocal8Bit("训练文件准备好了，可以开始训练"));
}
//选择训练文本
void stu_infor_Manage::on_pBselectFile_clicked()
{
 QString filepath=QFileDialog::getOpenFileName(this,QString::fromLocal8Bit("选择训练文件"),"F:\\Image\\Imagedata\\");
 ui->FilepathEdit->setText(filepath);
}
//训练成功
void stu_infor_Manage::train_over()
{
    QMessageBox::about(this,QString::fromLocal8Bit("提示"),QString::fromLocal8Bit("训练完成"));
    train->quit();
}
//开始训练文件
void stu_infor_Manage::on_pBstartrain_clicked()
{
    if(ui->FilepathEdit->text()==nullptr)
    {
        QMessageBox::about(this,QString::fromLocal8Bit("提示"),QString::fromLocal8Bit("请选择训练文本"));
        return;
    }
    QString filepath=ui->FilepathEdit->text();
    try {
        //传输训练文件路径
        train->SetFilepath(filepath);
        train->start();//间接调用run()
        QMessageBox::about(this,QString::fromLocal8Bit("提示"),QString::fromLocal8Bit("正在训练，请稍候"));
    }  catch (exception e) {
        QMessageBox::about(this,QString::fromLocal8Bit("提示"),QString::fromLocal8Bit("训练失败！"));
    }
}
//添加学生信息到数据库中
void stu_infor_Manage::on_pB_AddStu_clicked()
{
if(ui->numberEdit->text()==nullptr||ui->nameEdit->text()==nullptr||ui->SexEdit->text()==nullptr||ui->AgeEdit->text()==nullptr)
    QMessageBox::about(this,QString::fromLocal8Bit("提示"),QString::fromLocal8Bit("请将信息输入完整"));
    QString sql_str=QString("select * from Student where number='%1'").arg(ui->numberEdit->text());
    QSqlQuery query_str(sql_str);
    if(query_str.next())
   {
        QMessageBox::about(this,QString::fromLocal8Bit("提示"),QString::fromLocal8Bit("学生信息已存在！"));
}
    QSqlQuery query;
    QString sql=QString("insert into Student (Number,Name,Sex,Age)");
    sql +=QString("values('%1','%2','%3','%4')").arg(ui->numberEdit->text().toInt()).arg(ui->nameEdit->text())
            .arg(ui->SexEdit->text()).arg(ui->AgeEdit->text().toInt());
    bool ok=query.exec(sql);


    if(ok)
    {
        QMessageBox::about(this,QString::fromLocal8Bit("提示"),QString::fromLocal8Bit("恭喜，添加成功！"));
    }
    else{
        QMessageBox::about(this,QString::fromLocal8Bit("提示"),QString::fromLocal8Bit("添加失败！"));
    }
}
